<template>
  <div class="setup-privacy-container">
    <el-card>
      <el-form
        ref="privacyFormRef"
        :model="privacyForm"
        :rules="privacyRules"
        label-width="100px"
        class="privacy-form"
      >
        <el-form-item label="认证时间">
          <span class="auth-time">{{ authTime }}</span>
        </el-form-item>
        <el-form-item v-if="Number(privacyTimeValue) === 0" label="管理员电话">
          <el-input
            disabled
            :model-value="hidden(privacyForm.phone, 3, 4)"
            placeholder="请输入管理员电话"
          />
        </el-form-item>
        <el-form-item v-else label="管理员电话" prop="phone">
          <el-input v-model="privacyForm.phone" disabled placeholder="请输入管理员电话" />
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="privacyForm.code" maxlength="6" placeholder="请输入验证码">
            <template #append>
              <el-button
                class="code-btn"
                type="primary"
                :loading="codeLoading"
                :disabled="codeDisabled"
                @click="getCode"
              >
                <span v-if="!codeLoading && !countdownValue">获取验证码</span>
                <span v-else-if="codeLoading">发送中...</span>
                <span v-else>{{ countdownValue }}s</span>
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="submitLoading" @click="submitForm"> 确定 </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, computed, onUnmounted } from 'vue'
  import { ElMessage, FormInstance } from 'element-plus'
  import { PhoneService } from '@/api/setupApi'
  import { UserGetCodeParam, UserLoginParam } from '@/api/model/setupModel'
  import { ApiStatus } from '@/utils/http/status'
  import { encrypt } from '@/utils/rsaEncrypt'

  const TIME_COUNT = 120 // 更改倒计时时间

  // 表单引用
  const privacyFormRef = ref<FormInstance>()

  // 数据状态
  const submitLoading = ref(false)
  const codeLoading = ref(false)
  const countdownValue = ref(0)
  const privacyTimeValue = ref(0)
  const authTime = ref('')
  const timer = ref<NodeJS.Timeout | null>(null)

  // 隐私认证表单
  const privacyForm = reactive({
    phone: '',
    code: ''
  })

  // 表单验证规则
  const privacyRules = {
    phone: [
      { required: true, message: '请输入管理员电话', trigger: 'blur' },
      { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
  }

  // 计算验证码按钮是否禁用
  const codeDisabled = computed(() => {
    return !privacyForm.phone || countdownValue.value > 0
  })

  // 获取管理员电话
  const getPhone = async () => {
    try {
      const res = await PhoneService.getAdminPhone()
      if (res.code === ApiStatus.success) {
        privacyForm.phone = res.data || ''
      } else {
        ElMessage.error(res.message || '获取管理员电话失败')
      }
    } catch (error) {
      console.error('获取管理员电话异常:', error)
      ElMessage.error('获取管理员电话失败')
    }
  }

  // 获取验证码
  const getCode = async () => {
    if (!privacyForm.phone) {
      ElMessage.error('请填写手机号')
      return
    }

    if (!/^1[3456789]\d{9}$/.test(privacyForm.phone)) {
      ElMessage.error('请填写正确手机号')
      return false
    }

    if (countdownValue.value > 0) return

    codeLoading.value = true

    try {
      const param: UserGetCodeParam = {
        phone: privacyForm.phone
      }

      const res = await PhoneService.getPrivacyCode(param)
      if (res.code === ApiStatus.success) {
        ElMessage.success('发送成功，请注意查看手机短信')

        // 启动倒计时
        countdownValue.value = TIME_COUNT
        if (timer.value) clearInterval(timer.value)
        timer.value = setInterval(() => {
          countdownValue.value--
          if (countdownValue.value <= 0 && timer.value) {
            clearInterval(timer.value)
            timer.value = null
          }
        }, 1000)
      } else {
        ElMessage.error(res.message || '发送验证码失败')
      }
    } catch (error) {
      console.error('发送验证码异常:', error)
      ElMessage.error('发送验证码失败')
    } finally {
      codeLoading.value = false
    }
  }

  // 提交隐私认证
  const submitForm = async () => {
    if (!privacyFormRef.value) return

    await privacyFormRef.value.validate(async (valid) => {
      if (valid) {
        submitLoading.value = true

        try {
          const param: UserLoginParam = {
            code: encrypt(privacyForm.code),
            username: encrypt(privacyForm.phone)
          }

          const res = await PhoneService.verifyPrivacyCode(param)
          if (res.code === ApiStatus.success && res.data === true) {
            ElMessage.success('二次认证成功，该认证24小时内有效，超过时间需要重新认证')

            // 更新认证时间
            const currentTime = new Date().getTime()
            localStorage.setItem('privacyTime', currentTime.toString())
            privacyTimeValue.value = currentTime
            updateAuthTimeDisplay()

            // 重置表单
            privacyForm.code = ''
          } else {
            ElMessage.error(res.message || '隐私认证失败')
          }
        } catch (error) {
          console.error('隐私认证异常:', error)
          ElMessage.error('隐私认证失败')
        } finally {
          submitLoading.value = false
        }
      }
    })
  }

  // 更新认证时间显示
  const updateAuthTimeDisplay = () => {
    if (Number(privacyTimeValue.value) === 0) {
      authTime.value = '未认证'
    } else {
      const time = new Date(Number(privacyTimeValue.value))
      const year = time.getFullYear()
      const month = String(time.getMonth() + 1).padStart(2, '0')
      const day = String(time.getDate()).padStart(2, '0')
      const hours = String(time.getHours()).padStart(2, '0')
      const minutes = String(time.getMinutes()).padStart(2, '0')
      authTime.value = `${year}-${month}-${day} ${hours}:${minutes}`
    }
  }

  // 中间部分隐藏手机号
  const hidden = (str: string, frontLen: number, endLen: number) => {
    if (!str) return ''

    let endLenData = 0
    if (str.length !== 2) {
      endLenData = endLen
    }
    const len = str.length - frontLen - endLenData
    let xing = ''
    for (let i = 0; i < len; i++) {
      xing += '*'
    }
    return str.substring(0, frontLen) + xing + str.substring(str.length - endLenData)
  }

  // 初始化
  onMounted(() => {
    getPhone()
    privacyTimeValue.value = parseInt(localStorage.getItem('privacyTime') || '0')
    updateAuthTimeDisplay()
  })

  // 组件销毁时清理定时器
  onUnmounted(() => {
    if (timer.value) {
      clearInterval(timer.value)
    }
  })
</script>

<style scoped lang="scss">
  .setup-privacy-container {
    padding: 20px;

    .privacy-form {
      width: 600px;
      margin: 0 auto;

      .el-form-item__label {
        font-weight: bold;
      }

      .auth-time {
        color: #409eff;
        font-weight: bold;
      }

      .el-input {
        width: 70%;

        :deep(.el-input__inner) {
          height: 38px;
        }
      }

      .el-button {
        height: 38px;
      }

      .code-btn {
        height: 38px;
      }
    }
  }

  // 响应式设计 - IPad Pro
  @media screen and (max-width: $device-ipad-pro) {
    .setup-privacy-container {
      padding: 15px;

      .privacy-form {
        width: 100%;
      }
    }
  }

  // 响应式设计 - IPad 竖屏
  @media screen and (max-width: $device-ipad-vertical) {
    .setup-privacy-container {
      padding: 15px;
    }
  }

  // 响应式设计 - IPad
  @media screen and (max-width: $device-ipad) {
    .setup-privacy-container {
      padding: 15px;
    }
  }

  // 响应式设计 - 手机
  @media screen and (max-width: $device-phone) {
    .setup-privacy-container {
      padding: 10px;

      .privacy-form {
        width: 100%;

        .el-input {
          width: 100%;
        }

        .el-form-item__label {
          width: 80px !important;
        }
      }
    }
  }
</style>
